﻿using Business.BookManagement;
using Business.BookManagement.Dto;
using Business.CheckPlanManagement.Dto;
using Business.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Domain.Repositories;
using System.Linq.Dynamic.Core;
using XCZ;

namespace Business.CheckPlanManagement
{
    public class CheckPlanAppService : BusinessWorkFlowAppService, ICheckPlanAppService
    {
        private const string FormName = "CheckPlan";
        private IRepository<CheckPlan, Guid> _repository;

        public CheckPlanAppService(
            IRepository<CheckPlan, Guid> repository
            )
        {
            _repository = repository;
        }
        #region 增删改查基础方法

        public async Task<CheckPlanDto> Get(Guid id)
        {
            var data = await _repository.GetAsync(id);
            var dto = ObjectMapper.Map<CheckPlan, CheckPlanDto>(data);
            return dto;
        }

        public async Task<PagedResultDto<CheckPlanDto>> GetAll(GetCheckPlanInputDto input)
        {
            var query = (await _repository.GetQueryableAsync()).WhereIf(!string.IsNullOrWhiteSpace(input.Filter), a => a.CPName.Contains(input.Filter));

            var totalCount = await query.CountAsync();
            var items = await query.OrderBy(input.Sorting ?? "Id")
                        .ToListAsync();

            var dtos = ObjectMapper.Map<List<CheckPlan>, List<CheckPlanDto>>(items);
            return new PagedResultDto<CheckPlanDto>(totalCount, dtos);
        }

        public async Task<CheckPlanDto> CreateOrUpdate(CreateOrUpdateCheckPlanDto input)
        {
            CheckPlan result = null;
            if (!input.Id.HasValue)
            {
                input.Id = GuidGenerator.Create();
                result = await _repository.InsertAsync(ObjectMapper.Map<CreateOrUpdateCheckPlanDto, CheckPlan>(input));

                //创建工作流
                // await WorkFlow.CreateWorkFlow(FormName, result);
            }
            else
            {
                var data = await _repository.GetAsync(input.Id.Value);
                result = await _repository.UpdateAsync(ObjectMapper.Map(input, data));
                //检查流程状态
                //await WorkFlow.CheckFormStatus(input.Id.Value, result);
            }
            return ObjectMapper.Map<CheckPlan, CheckPlanDto>(result);
        }

        public async Task Delete(List<Guid> ids)
        {
            foreach (var item in ids)
            {
                await _repository.DeleteAsync(item);
            }

        }
        #endregion
    }
}
